import mongoose, { Document, Schema } from 'mongoose'

export interface ITransaction extends Document {
  userId: Schema.Types.ObjectId
  orderId: string
  type: 'recharge' | 'gift' | 'withdraw'
  amount: number
  coins: number
  paymentMethod: 'alipay' | 'wechat'
  status: 'pending' | 'completed' | 'failed'
  description: string
  metadata: any
  completedAt?: Date
  createdAt: Date
  updatedAt: Date
}

const TransactionSchema = new Schema(
  {
    userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    orderId: { type: String, required: true, unique: true },
    type: {
      type: String,
      enum: ['recharge', 'gift', 'withdraw'],
      required: true,
    },
    amount: { type: Number, required: true },
    coins: { type: Number, required: true },
    paymentMethod: {
      type: String,
      enum: ['alipay', 'wechat'],
      required: true,
    },
    status: {
      type: String,
      enum: ['pending', 'completed', 'failed'],
      default: 'pending',
    },
    description: String,
    metadata: Schema.Types.Mixed,
    completedAt: Date,
  },
  {
    timestamps: true,
  }
)

// 创建索引
TransactionSchema.index({ userId: 1, createdAt: -1 })
TransactionSchema.index({ orderId: 1 }, { unique: true })
TransactionSchema.index({ status: 1, createdAt: -1 })

export const Transaction = mongoose.model<ITransaction>('Transaction', TransactionSchema)
